package com.kami.intercepter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.kami.annotation.IgnoreAuth;
import com.kami.entity.SysToken;
import com.kami.exception.IException;
import com.kami.service.SysTokenService;


/**
 * token验证
 * @author dong
 *
 */
@Component
public class AuthorizationInterceptor extends HandlerInterceptorAdapter{

	public static final String LOGIN_USER_KEY = "LOGIN_USER_KEY";
	
	@Autowired
	private SysTokenService tokenService;
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		IgnoreAuth annotation;
        if(handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(IgnoreAuth.class);
        }else{
            return true;
        }
        
        //如果有@IgnoreAuth注解，则不验证token
        if(annotation != null){
            return true;
        }
        
        //从header中获取token
        String token = request.getHeader("token");
        //如果header中不存在token，则从参数中获取token
        if(StringUtils.isBlank(token)){
            token = request.getParameter("token");
        }
		
        if (StringUtils.isBlank(token)) {
			throw new IException("token不能为空");
		}
        
        SysToken sysToken  = tokenService.queryToken(token);
        if (sysToken == null || sysToken.getExpireTime().getTime() < System.currentTimeMillis()) {
        	throw new IException("token失效,请重新登录");
		}
        
        request.setAttribute(LOGIN_USER_KEY, sysToken.getUserId());
		return true;
	}

	
	
	
}
